
/****************************************************************************/
/*Copyright (c) 2011, Florent DEVILLE.                                      */
/*All rights reserved.                                                      */
/*                                                                          */
/*Redistribution and use in source and binary forms, with or without        */
/*modification, are permitted provided that the following conditions        */
/*are met:                                                                  */
/*                                                                          */
/* - Redistributions of source code must retain the above copyright         */
/*notice, this list of conditions and the following disclaimer.             */
/* - Redistributions in binary form must reproduce the above                */
/*copyright notice, this list of conditions and the following               */
/*disclaimer in the documentation and/or other materials provided           */
/*with the distribution.                                                    */
/* - The names of its contributors cannot be used to endorse or promote     */
/*products derived from this software without specific prior written        */
/*permission.                                                               */
/* - The source code cannot be used for commercial purposes without         */ 
/*its contributors' permission.                                             */
/*                                                                          */
/*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         */
/*LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         */
/*FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            */
/*COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       */
/*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,      */
/*BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;          */
/*LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER          */
/*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT        */
/*LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN         */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/*POSSIBILITY OF SUCH DAMAGE.                                               */
/****************************************************************************/

#include "CTexture.h"

#include "RTMatrix33.h"

CTexture::CTexture() : _picture(0)
{
	_textureName = "";
}

CTexture::~CTexture()
{
	if (_picture != 0)
	{
		SDL_FreeSurface(_picture);
		_picture = 0;
	}
}

bool CTexture::loadTexture(const string& filename)
{
	_textureName = filename;

	//load the picture
	_picture=IMG_Load(_textureName.c_str());
	if(_picture == 0)
		return false;

	//lock the surface
	SDL_LockSurface(_picture);

	//picture width
	_width = _picture->w - 1;

	//picture height
	_height = _picture->h - 1;

	//picture bytes per pixel
	_bytesPerPixel = _picture->format->BitsPerPixel / 8;

	return true;
}

//return the color of the pixel for the point p in the triangle t.
//Solver using cramer's rule
CColor CTexture::getColor(const CVector3f& p, CPrimTriangle* const t)const
{
	//store the current point
	CVector3f pT = p;

	//get the vertices
	CVector3f* vertex = t->getVertices();

	if(t->_useTranslation)
	{
		pT = p + t->_offset;
		vertex = t->_uvTranslated;
	}

	//calculate D
	RTMatrix33 mD(vertex[0], vertex[1], vertex[2]); 
	float D = mD.det();

	//calculate A1
	RTMatrix33 mA1(pT, vertex[1], vertex[2]);
	float A1 = mA1.det();

	//calculate A2
	RTMatrix33 mA2(vertex[0], pT, vertex[2]);
	float A2 = mA2.det();

	//calculate barycentric coordinates
	float x = A1 / D;
	float y = A2 / D;
	float z = 1 - x - y;

	//get the uvmap
	CVector3f* uv = t->getUV();

	//calculate uv map of p
	float up = uv[0].x*x + uv[1].x*y + uv[2].x*z;
	float vp = uv[0].y*x + uv[1].y*y + uv[2].y*z;

	//calculate the pixels coordinate
	int offsetX = int(up * _width);
	int offsetY = int(vp * _height);

	//saturate the pixel coordinate inside the texture (allow tiles)
	if(offsetX >= (int)_width || offsetX < 0) offsetX %= _width;
	if(offsetY >= (int)_height || offsetY < 0) offsetY %= _height;

	//calculate the position in the array of pixels
	unsigned int offset = offsetY * _picture->pitch + offsetX * _bytesPerPixel;

	//get the pixel color
	unsigned char* pixels = (unsigned char*)_picture->pixels;

	float R = (float)pixels[offset] / 255;
	float G = (float)pixels[offset+1] / 255;
	float B = (float)pixels[offset+2] / 255;

	return CColor(R, G, B, 1);
}
